<?php
namespace app\common\model;
use think\Validate;

class ArticleType extends Common
{
    protected $rule = [
        'type_name' => 'require|max:25'
    ];

    protected $msg = [
        'type_name.require' => '分类名称必须',
        'type_name.max' => '名称最多不能超过25个字符'
    ];


    /**
     * 后台分类 树形列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList()
    {
        return $this->select();
    }


    /**
     * 分类添加
     * @param $data
     * @return array
     */
    public function addData($data)
    {
        $validate = new Validate($this->rule,$this->msg);
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data'=>''
        ];
        if(!$validate->check($data))
        {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        }
        else
        {
            if(!$this->allowField(true)->save($data))
            {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            }
        }
        return $result;
    }


    /**
     * 分类修改
     * @param $data
     * @return array
     */
    public function editData($data)
    {
        $validate = new Validate($this->rule,$this->msg);
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data' => ''
        ];
        if(!$validate->check($data))
        {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        }
        else
        {
            if(!$this->allowField(true)->save($data, ['id' => $data['id']]))
            {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            }
        }
        return $result;
    }


    /**
     * 获取文章分类列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function articleTypeList()
    {
        $result = [
            'status' => true,
            'msg' => '获取成功',
            'data' => []
        ];

        $list = $this->field('id, pid, type_name')->select();

        if(!$list->isEmpty())
        {
            $articleModel = new Article();
            foreach ($list as $key => &$value) {
                $value['article'] = $articleModel->articleList($value['id'])['data'];
                if (!$value['article']) {
                    unset($list[$key]);
                }
            }
            $result['data'] = array_values($list->toArray());
        }
        return $result;
    }


    /**
     * 文章分类 与 文章 一对多关联
     * @return \think\model\relation\HasMany
     */
    public function comments()
    {
        return $this->hasMany('Article');
    }
}